<template>
  <ContentWrap class="congig-page !mb-0">
    <div class="mb-20px">
      <span class="text-16px font-bold">食谱审核人员配置</span>
    </div>
    
    <el-form :model="formData" label-width="120px" ref="formRef">
      <el-form-item label="审核人员">
        <UserSelectButton v-model="selectedUsers" />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>

<script setup lang="ts">
import { RecipeConfigApi } from '@/api/school/recipe/config'

/** 系统配置 列表 */
defineOptions({ name: 'RecipeConfig' })

const message = useMessage() // 消息弹窗

const formRef = ref() // 表单 Ref
const formData = ref({
  id: undefined,
  userIds: []
})
const selectedUsers = ref<any[]>([]) // 选中的用户列表

/** 查询详情 */
const getConfig = async () => {
  try {
    const data: any = await RecipeConfigApi.getRecipeConfig()
    formData.value = {
      id: data.id,
      userIds: data.userIds || []
    }
    
    // 初始化选中的用户列表
    selectedUsers.value = (data.userIds || []).map((id: any, index: number) => {
      return {
        id,
        nickname: (data.userNames || [])[index] || ''
      }
    })
  } catch (err) {
    // 如果没有配置，则初始化一个空的配置
    formData.value = {
      id: undefined,
      userIds: []
    }
    selectedUsers.value = []
  }
}

/** 提交表单 */
const submitForm = async () => {
  try {
    // 获取选中的用户ID列表
    const userIds = selectedUsers.value.map((user: any) => user.id)
    
    // 准备提交数据
    const submitData: any = {
      userIds: userIds
    }
    
    // 如果存在ID，则为更新操作，否则为创建操作
    if (formData.value.id) {
      submitData.id = formData.value.id
      await RecipeConfigApi.updateRecipeConfig(submitData)
      message.success('更新成功')
    } else {
      const res: any = await RecipeConfigApi.createRecipeConfig(submitData)
      formData.value.id = res.id
      message.success('创建成功')
    }
    
    // 重新获取配置
    await getConfig()
  } catch (err) {
    message.error('操作失败: ' + (err as any).message)
  }
}

/** 初始化 **/
onMounted(() => {
  getConfig()
})
</script>
<style lang="scss" scoped>
.congig-page {
  min-height: $content-height;
}
</style>